import requests
import urllib3
import json

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

username = "admin"
password = "1a.cisco"
apic_host = "10.138.225.4"
my_headers = {"content-type": "application/json"}


def get_token(ip):
    client = requests.session()
    login_url = 'https://' + ip + '/api/aaaLogin.json'
    name_pwd = {'aaaUser': {'attributes': {'name': username, 'pwd': password}}}
    body = client.post(login_url, json=name_pwd, headers=my_headers, verify=False).json()
    token = body['imdata'][0]['aaaLogin']['attributes']['token']
    return token


def create_interface_policy_group_pc(token, ip, interface_policy_group_name, lagT,
                                     AAEP_name):  # lagT = 'node' or 'link' node为vpc、link为pc
    my_headers = {"content-type": "application/json", "Cookie": "APIC-login=; APIC-preState=; APIC-cookie=" + token}
    client = requests.session()
    url = 'https://' + ip + '/api/node/mo/uni/infra/funcprof/.json'
    json_data = {
        "infraAccBndlGrp": {
            "attributes": {
                "dn": "uni/infra/funcprof/accbundle-" + interface_policy_group_name,
                "lagT": lagT,
                "name": "" + interface_policy_group_name,
                "rn": "accbundle-" + interface_policy_group_name,
                "status": "created,modified"
            },
            "children": [
                {
                    "infraRsAttEntP": {
                        "attributes": {
                            "tDn": "uni/infra/attentp-" + AAEP_name + "",
                            "status": "created,modified"
                        },
                        "children": []
                    }
                }
            ]
        }
    }

    body = client.post(url, json=json_data, headers=my_headers, verify=False).json()
    return body


dict_data = {'totalCount': '1', 'imdata': [{'fvTenant': {
    'attributes': {'childAction': '', 'descr': '', 'dn': 'uni/tn-Heroes', 'extMngdBy': '', 'lcOwn': 'local',
                   'modTs': '2018-11-29T13:29:29.152+00:00', 'monPolDn': 'uni/tn-common/monepg-default',
                   'name': 'Heroes', 'nameAlias': '', 'ownerKey': '', 'ownerTag': '', 'status': '', 'uid': '15374'}}}]}


def pprint_json(json_data):
    print(json.dumps(json_data, indent=1, sort_keys=True))


if __name__ == "__main__":
    token = get_token(apic_host)
    pprint_json(token)
    r = create_interface_policy_group_pc(token, apic_host, 'test_api_vpc1', 'node', '1003')
    print(json.dumps(r, indent=1, sort_keys=True))
